﻿using System;
using System.Drawing.Imaging;
using System.IO;

namespace LeanUi.ImageBundle
{
    public class DataUriBuilder
    {
        public string GenerateCss(ImageRect[] imageRects)
        {
            return imageRects.Join(GenerateCssRule, Environment.NewLine);
        }

        private string GenerateCssRule(ImageRect imageRect)
        {
            var data = ToDataUri(imageRect);
            var name = NamingHelper.GetBackgroundSpriteClassFor(imageRect.FullPath);
            var repeat = imageRect.BackgroundType == BackgroundType.Vertical
                       ? "repeat-x"
                       : "repeat-y";
            return string.Format(CodeGenerationTemplates.CssBgSpriteRule_3, name, data, repeat);
        }

        private string ToDataUri(ImageRect imageRect)
        {
            using (var ms = new MemoryStream())
            {
                imageRect.Image.Save(ms, ImageFormat.Png);
                var bytes = ms.ToArray();
                var base64 = Convert.ToBase64String(bytes);
                return "data:image/png;base64," + base64;
            }
        }
    }
}